from enum import Enum
from typing import Dict, Any, List

class ConflictStrategy(Enum):
    KEEP_LOCAL = "keep_local"
    KEEP_REMOTE = "keep_remote"
    MERGE = "merge"
    MANUAL = "manual"

class MetadataConflictResolver:
    STRATEGY_WEIGHT = {
        'last_modified': 0.8,
        'bpm_accuracy': 0.6,
        'cover_art': 0.9,
        'tag_completeness': 0.7
    }

    def __init__(self, strategy: ConflictStrategy = ConflictStrategy.MERGE):
        self.strategy = strategy
        
    def resolve(self, local: Dict[str, Any], remote: Dict[str, Any]) -> Dict[str, Any]:
        if self.strategy == ConflictStrategy.KEEP_LOCAL:
            return local
            
        if self.strategy == ConflictStrategy.KEEP_REMOTE:
            return remote
            
        if self.strategy == ConflictStrategy.MANUAL:
            raise ConflictRequiresManualReview()
            
        # MERGE策略
        merged = {}
        all_keys = set(local.keys()) | set(remote.keys())
        
        for key in all_keys:
            l_val = local.get(key)
            r_val = remote.get(key)
            
            if l_val is None and r_val is not None:
                merged[key] = r_val
            elif r_val is None and l_val is not None:
                merged[key] = l_val
            elif l_val == r_val:
                merged[key] = l_val
            else:
                merged[key] = self._weighted_merge(
                    key, [l_val, r_val])
                    
        return merged
        
    def _weighted_merge(self, key: str, values: List[Any]) -> Any:
        weights = []
        for value in values:
            total_weight = 0
            for factor, weight in self.STRATEGY_WEIGHT.items():
                if hasattr(value, factor):
                    total_weight += weight
            weights.append(total_weight)
            
        return values[weights.index(max(weights))]